<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加分类 -->
      <el-col>
        <el-button class="addCate" type="primary" @click="addCateOpen"
          >添加分类</el-button
        >
      </el-col>
      <!-- 分类表格 -->
      <tree-table
        :data="allCateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        :show-row-hover="false"
        border
      >
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 分类排序 -->
        <template slot="cate" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="set" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="queryCate(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeCateById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 14]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 编辑对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="EditCateDialogVisible"
      width="50%"
      @close="EditCateDialogClose"
    >
      <el-form
        :model="cateRow"
        :rules="rules"
        ref="cateForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="cateRow.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditCate(cateRow.cat_id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 添加分类 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose"
    >
      <el-form
        :model="addCateFrom"
        :rules="addCateRules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateFrom.cat_name"></el-input>
        </el-form-item>
        <!-- 级联选择器 -->
        <el-form-item label="父级分类" >
          <el-cascader
            v-model="valueArr"
            :options="ParentCateList"
            :props="parentProps"
            @change="handleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      queryInfo: {
        //获取分类列表需要传入的参数
        pagenum: 1, //第一页
        pagesize: 5, //显示5条数据
      },
      EditCateDialogVisible: false, //控制修改对话框的显示与隐藏
      allCateList: [], //商品分类数据
      total: 0, //总共的数据
      cateRow: {}, //每行分类的数据
      addCateFrom: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      addCateDialogVisible: false, //添加分类对话框显示与隐藏
      ParentCateList: [], //父级分类列表
      valueArr: [], //联级中选择的值
      // 联级选择器绑定的数据
      parentProps: {
        value: "cat_id", //需要显示的值
        label: "cat_name", //看到的值
        children: "children", //绑定的嵌套属性
        expandTrigger: "hover", //鼠标移入显示
         //是否可以选择任意级别
      },
      columns: [
        {
          label: "分类名称", //标题名
          prop: "cat_name", //需要显示的分类名称
        },
        {
          label: "是否有效", //标题名
          prop: "cat_deleted",
          type: "template", //模板类型
          template: "isOk", //插槽名称
        },

        {
          label: "分类排序", //标题名
          prop: "cat_level",
          type: "template", //模板类型
          template: "cate", //插槽名称
        },

        {
          label: "操作", //标题名
          type: "template", //模板类型
          template: "set", //插槽名称
        },
      ],
      rules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 2,
            max: 10,

            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
      },

      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 2,
            max: 10,

            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },

  created() {
    this.getCateList(); //获取商品分类列表
  },

  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status == 200) {
        this.allCateList = res.data.result; //获取到的所有分类列表赋值到数组中
        this.total = res.data.total;
        this.$message.success("获取商品分类列表成功");
      } else {
        this.$message.error("获取商品分类列表失败");
      }
    },
    //每页条数改变时触发
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    //当前页改变时触发
    handleCurrentChange(newNUm) {
      this.queryInfo.pagenum = newNUm;
      this.getCateList();
    },

    //查询分类
    async queryCate(id) {
      const { data: res } = await this.$http.get("categories/" + id);
      if (res.meta.status == 200) {
        this.cateRow = res.data; //每行的分类对象赋值
      }

      this.EditCateDialogVisible = true;
    },
    //修改对话框关闭时重置表单
    EditCateDialogClose() {
      this.$refs.cateForm.resetFields(); //
      this.cateRow = {}; //关闭后需要把cateRow赋值为空，不然会有上一次的缓存
    },

    //修改后点击确认完成修改
    EditCate(id) {
      this.$refs.cateForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put("categories/" + id, {
            cat_name: this.cateRow.cat_name,
          });

          if (res.meta.status == 200) {
            this.$message.success("修改分类成功");
            this.getCateList();
            this.EditCateDialogVisible = false;
          } else {
            this.$message.error("修改分类失败");
          }
        } else {
          return
        }
      });
    },
    //通过id删除分类
    async removeCateById(id) {
      const val = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      if (val == "confirm") {
        const { data: res } = await this.$http.delete("categories/" + id);
        if (res.meta.status == 200) {
          this.$message.success("成功删除该分类");
          this.getCateList();
        } else {
          this.$message.erro("删除失败");
        }
      } else {
        this.$message.info("已取消删除");
      }
    },

    //添加分类对话框显示
    addCateOpen() {
      this.getParentCateList(); //打开前调用父级分类列表函数
      this.addCateDialogVisible = true; //对话框显示
    },

    //获取父级分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status == 200) {
        this.ParentCateList = res.data;
      }
    },
    //回调返回选联级中选择的值
    handleChange() {
      console.log(this.valueArr);
      //如果valueArr数组里面的值大于0，说明选择了父级，否则没有选择父级
      if(this.valueArr.length>0){
        this.addCateFrom.cat_pid = this.valueArr[this.valueArr.length-1]//父级id
        this.addCateFrom.cat_level=this.valueArr.length//当前分类等级
      }else{
         this.addCateFrom.cat_pid=0//父级id
         this.addCateFrom.cat_level=0//当前分类等级
      }
    },

    //添加分类对话框关闭后，重置表单
    addCateDialogClose(){
      this.$refs.addForm.resetFields()//重置表单
      this.valueArr=[]
      this.addCateFrom.cat_pid=0
      this.addCateFrom.cat_level=0
    },
    
    //点击确定，添加分类
     addCate(){
      this.$refs.addForm.validate(async valid=>{
        if(valid){
          const {data:res}=await this.$http.post('categories',this.addCateFrom)
          if(res.meta.status==201){
            this.$message.success('添加分类成功')
            this.getCateList()
            this.addCateDialogVisible=false
            
          }else{
            this.$message.error('添加分类失败')
          }
        }else{
          return
        }
      })
     
       
    }
  },
};
</script>

<style lang="less" scoped>
.addCate {
  margin-bottom: 15px;
}


</style>